package cn.edu.nju.ws.aquila.ui.servlets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import cn.edu.nju.ws.aquila.database.DBConnectionFactory;

public class LoginServlet extends HttpServlet{
//    private Logger logger = Logger.getLogger(LoginServlet.class.getName());
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String uid = req.getParameter("uid");
		String pwd = req.getParameter("pwd") ;
		if(uid==null||pwd==null){
			req.setAttribute("message", "error") ;
			req.getRequestDispatcher("./login.jsp").forward(req, resp) ;
		}
		Connection con = DBConnectionFactory.getConnection();
		PreparedStatement ps;
		try {
			ps = con.prepareStatement("select id from usr where name=? and pwd=?");
			ps.setString(1, uid.trim()) ;
			ps.setString(2, pwd.trim()) ;
			ResultSet rs = ps.executeQuery();
			if(rs.next()){
				String name = uid.trim();
				req.getSession().setAttribute("user", name) ;
				req.getRequestDispatcher("./main_datasource.jsp").forward(req, resp) ;
			}else{
				req.setAttribute("message", "error") ;
				req.getRequestDispatcher("./login.jsp").forward(req, resp) ;
			}
			rs.close();
			ps.close();
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
    
}
